package com.ruoyi.project.zerocarbon.controller;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.zerocarbon.domain.*;
import com.ruoyi.project.zerocarbon.domain.export.DeclarationZhejiangExport;
import com.ruoyi.project.zerocarbon.domain.export.DeclarationZhejiangRankingExport;
import com.ruoyi.project.zerocarbon.mapper.DeclarationZhejiangMapper;
import com.ruoyi.project.zerocarbon.mapper.DeclareJudgeMapper;
import com.ruoyi.project.zerocarbon.mapper.DeclareRankingMapper;
import com.ruoyi.project.zerocarbon.service.IDeclarationZhejiangService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @类名: AuditController
 * @描述:
 * @作者:
 * @日期: 2021/6/26 15:07
 */
@Slf4j
@Api("浙江省导出,导出一条时，只需要传id")
@RequestMapping("/declarationzj/export")
@RestController
public class DeclarationZhejiangExportController extends BaseController {
    @Autowired
    private DeclarationZhejiangMapper declarationZhejiangMapper;
    @Autowired
    private DeclareJudgeMapper declareJudgeMapper;
    @Autowired
    private IDeclarationZhejiangService declarationZhejiangService;
    @Autowired
    private DeclareRankingMapper declareRankingMapper;
    @Autowired
    private TokenService tokenService;

    private List<DeclarationZhejiang> selectOne(Long id){
        DeclarationZhejiang declaration = declarationZhejiangMapper.selectDeclarationDetailZhejiangById(id);
        List<DeclarationZhejiang> list = Arrays.asList(declaration);
        return list;
    }

    private DeclarationZhejiang selectRankingOne(Long id){
        DeclarationZhejiang declaration = declarationZhejiangMapper.selectDeclarationDetailZhejiangById(id);
        List<DeclareJudge> declareJudges = declareJudgeMapper.selectDeclareJudgeByDecorationId(declaration.getId());
        declaration.setDeclareJudges(declareJudges);
        if (!CollectionUtils.isEmpty(declareJudges)){
            Integer sum = declareJudges.stream().mapToInt(DeclareJudge::getScore).sum();
            declaration.setScore(Math.round(sum/3));
        }else {
            declaration.setScore(0);
        }
        DeclareRanking declareRanking = declareRankingMapper.selectDeclareRankingByDeclarationId(declaration.getId());
        Integer score = 0;
        if (declareRanking != null){
            score = declareRanking.getScore();
        }
        int ranking = declarationZhejiangMapper.getRankingNum(score) + 1;
        declaration.setRanking(ranking);

        return declaration;
    }

    private List<DeclarationZhejiang> selectList(List<Long> idList){
        List<DeclarationZhejiang> list = new ArrayList<>();
        for (Long id:idList){
            DeclarationZhejiang declaration = declarationZhejiangMapper.selectDeclarationDetailZhejiangById(id);
            if (declaration != null){
                list.add(declaration);
            }
        }
        return list;
    }

    /**
     * 项目报名列表
     * @param declarationZhejiang
     * @return
     */
    @ApiOperation("项目报名列表导出")
    @PostMapping("/signUp/list")
    public AjaxResult signUpList(@Validated @RequestBody DeclarationZhejiang declarationZhejiang) {
        List<DeclarationZhejiang> list = new ArrayList<>();
        if (declarationZhejiang.getId() != null){
            list = selectOne(declarationZhejiang.getId());
        }else if (CollectionUtils.isNotEmpty(declarationZhejiang.getIdList())){
            list = selectList(declarationZhejiang.getIdList());
        }else {
            startPage();
            declarationZhejiang.setSaveType(1);
            if (declarationZhejiang.getAuditStatus() == null) {
            } else if (declarationZhejiang.getAuditStatus() == 13) {
                declarationZhejiang.setAuditStatusList(Arrays.asList(13, 21, 22, 23, 24, 25));
            }
            list = declarationZhejiangService.selectDeclarationZhejiangListExport(declarationZhejiang);
        }
        List<DeclarationZhejiangExport> exportList = getExportList(list);

        ExcelUtil<DeclarationZhejiangExport> util = new ExcelUtil<DeclarationZhejiangExport>(DeclarationZhejiangExport.class);
        return util.exportExcel(exportList, "项目报名列表");
    }

    /**
     * 项目上报列表
     * @param declarationZhejiang
     * @return
     */
    @ApiOperation("项目上报列表导出")
    @PostMapping("/report/list")
    public AjaxResult reportList(@Validated @RequestBody DeclarationZhejiang declarationZhejiang) {
        List<DeclarationZhejiang> list = new ArrayList<>();
        if (declarationZhejiang.getId() != null){
            list = selectOne(declarationZhejiang.getId());
        }else if (CollectionUtils.isNotEmpty(declarationZhejiang.getIdList())){
            list = selectList(declarationZhejiang.getIdList());
        }else {
            startPage();
            if (declarationZhejiang.getAuditStatus() == null || declarationZhejiang.getAuditStatus() < 13) {
                declarationZhejiang.setAuditStatusList(Arrays.asList(13,21,22,24,25));
            }
            list = declarationZhejiangService.selectDeclarationZhejiangListExport(declarationZhejiang);
        }
        List<DeclarationZhejiangExport> exportList = getExportList(list);

        ExcelUtil<DeclarationZhejiangExport> util = new ExcelUtil<DeclarationZhejiangExport>(DeclarationZhejiangExport.class);
        return util.exportExcel(exportList, "项目上报列表");
    }

    /**
     * 项目审核列表导出
     * @param declarationZhejiang
     * @return
     */
    @ApiOperation("项目审核列表导出")
    @PostMapping("/check/list")
    public AjaxResult checkList(@Validated @RequestBody DeclarationZhejiang declarationZhejiang) {
        List<DeclarationZhejiang> list = new ArrayList<>();
        if (declarationZhejiang.getId() != null){
            list = selectOne(declarationZhejiang.getId());
        }else if (CollectionUtils.isNotEmpty(declarationZhejiang.getIdList())){
            list = selectList(declarationZhejiang.getIdList());
        }else {
            startPage();
            if (declarationZhejiang.getAuditStatus() == null || declarationZhejiang.getAuditStatus() < 21) {
                declarationZhejiang.setAuditStatusList(Arrays.asList(21, 24));
            }
            list = declarationZhejiangService.selectDeclarationZhejiangListExport(declarationZhejiang);
        }
        List<DeclarationZhejiangExport> exportList = getExportList(list);

        ExcelUtil<DeclarationZhejiangExport> util = new ExcelUtil<DeclarationZhejiangExport>(DeclarationZhejiangExport.class);
        return util.exportExcel(exportList, "项目审核列表");
    }

    /**
     * 项目分配列表
     * @param declarationZhejiang
     * @return
     */
    @ApiOperation("项目分配列表导出")
    @PostMapping("/distribution/list")
    public AjaxResult distributionList(@Validated @RequestBody DeclarationZhejiang declarationZhejiang) {
        List<DeclarationZhejiang> list = new ArrayList<>();
        if (declarationZhejiang.getId() != null){
            list = selectOne(declarationZhejiang.getId());
        }else if (CollectionUtils.isNotEmpty(declarationZhejiang.getIdList())){
            list = selectList(declarationZhejiang.getIdList());
        }else {
            startPage();
            if (declarationZhejiang.getAuditStatus() == null || declarationZhejiang.getAuditStatus() < 21) {
                declarationZhejiang.setAuditStatus(24);
            }
            list = declarationZhejiangService.selectDeclarationZhejiangList(declarationZhejiang);
        }
        List<DeclarationZhejiangExport> exportList = getExportList(list);

        ExcelUtil<DeclarationZhejiangExport> util = new ExcelUtil<DeclarationZhejiangExport>(DeclarationZhejiangExport.class);
        return util.exportExcel(exportList, "项目分配列表");
    }

    /**
     * 项目评分列表
     * @param declarationZhejiang
     * @return
     */
    @ApiOperation("项目评分列表导出")
    @PostMapping("/judge/list")
    public AjaxResult judgeList(@Validated @RequestBody DeclarationZhejiang declarationZhejiang) {
        List<DeclarationZhejiang> list = new ArrayList<>();
        ExcelUtil<DeclarationZhejiangExport> util = new ExcelUtil<DeclarationZhejiangExport>(DeclarationZhejiangExport.class);
        if (declarationZhejiang.getId() != null){
            DeclarationZhejiang declaration = selectRankingOne(declarationZhejiang.getId());
            list = Arrays.asList(declaration);
        }else if (CollectionUtils.isNotEmpty(declarationZhejiang.getIdList())){
            for (Long id:declarationZhejiang.getIdList()){
                list.add(selectRankingOne(id));
            }
        }else {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            String groupName = loginUser.getUser().getRemark();
            declarationZhejiang.setGroupName(groupName);
            if (StringUtils.isEmpty(groupName)){
                List<DeclarationZhejiangExport> exportList = new ArrayList<>();
                return util.exportExcel(exportList, "项目评分列表");
            }

            declarationZhejiang.setDistributionStatus(1);
            if (declarationZhejiang.getAuditStatus() == null || declarationZhejiang.getAuditStatus() < 23) {
                declarationZhejiang.setAuditStatus(24);
            }
            Integer pageNum = declarationZhejiang.getPageNum() != null ? declarationZhejiang.getPageNum() : 1;
            Integer pageSize = declarationZhejiang.getPageSize() != null ? declarationZhejiang.getPageSize() : 5000;
            String orderBy = "id desc";
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<DeclarationZhejiang> groupDecorationList;
            if (declarationZhejiang.getJudgeStatus() != null && declarationZhejiang.getJudgeStatus() ==0){
                declarationZhejiang.setUserName(loginUser.getUser().getUserName());
                groupDecorationList = declarationZhejiangMapper.getGroupDecorationListAndNoJudgeStatus(declarationZhejiang);
            }else if (declarationZhejiang.getJudgeStatus() != null && declarationZhejiang.getJudgeStatus() > 0){
                declarationZhejiang.setUserName(loginUser.getUser().getUserName());
                groupDecorationList = declarationZhejiangMapper.getGroupDecorationListAndJudgeStatus(declarationZhejiang);
            }else {
                groupDecorationList = declarationZhejiangMapper.getGroupDecorationList(declarationZhejiang);
            }
//            list = declarationZhejiangService.getJudgeDecorationListByVoList(groupDecorationList,declarationZhejiang.getJudgeStatus(),loginUser.getUser().getUserName());
            if (CollectionUtils.isNotEmpty(groupDecorationList)){
                List<Long> longList = groupDecorationList.stream().map(DeclarationZhejiang::getId).collect(Collectors.toList());
                DeclarationZhejiang model = new DeclarationZhejiang();
                model.setIdList(longList);
                list = declarationZhejiangService.selectDeclarationZhejiangList(model);
            }
        }
        List<DeclarationZhejiangExport> exportList = getExportList(list);

        return util.exportExcel(exportList, "项目评分列表");
    }

    private List<DeclarationZhejiangExport> getExportList(List<DeclarationZhejiang> list){
        List<DeclarationZhejiangExport> exportList = new ArrayList<>();
        for (DeclarationZhejiang declaration:list){
            DeclarationZhejiangExport exportModel = new DeclarationZhejiangExport();
            BeanUtils.copyProperties(declaration,exportModel);
            if (CollectionUtils.isNotEmpty(declaration.getFunds())){
                String projectExpenditure = declaration.getFunds().stream().map(DeclareFunds::getProjectExpenditure).collect(Collectors.joining("\n"));
                String projectAmount = declaration.getFunds().stream().map(DeclareFunds::getProjectExpenditure).collect(Collectors.joining("\n"));
                exportModel.setActivityContent(projectExpenditure);
                exportModel.setProjectAmount(projectAmount);
            }

            if (CollectionUtils.isNotEmpty(declaration.getImplementationPlans())){
                String activitySituation = declaration.getImplementationPlans().stream().map(DeclareImplementationPlan::getActivitySituation).collect(Collectors.joining("\n"));
                String activityContent = declaration.getImplementationPlans().stream().map(DeclareImplementationPlan::getActivityContent).collect(Collectors.joining("\n"));           String activityHours = declaration.getImplementationPlans().stream().map(DeclareImplementationPlan::getActivityHours).collect(Collectors.joining("\n"));
                exportModel.setActivitySituation(activitySituation);
                exportModel.setActivityContent(activityContent);
                exportModel.setActivityHours(activityHours);
            }

            if (CollectionUtils.isNotEmpty(declaration.getExternalOrganizations())){
                String organizationInfo = declaration.getExternalOrganizations().stream().map(DeclareExternalOrganization::getOrganizationInfo).collect(Collectors.joining("\n"));
                String supportIssues = declaration.getExternalOrganizations().stream().map(DeclareExternalOrganization::getSupportIssues).collect(Collectors.joining("\n"));
                exportModel.setOrganizationInfo(organizationInfo);
                exportModel.setSupportIssues(supportIssues);
            }

            if (CollectionUtils.isNotEmpty(declaration.getMediaCoverages())){
                String mediaName = declaration.getMediaCoverages().stream().map(DeclareMediaCoverage::getMediaName).collect(Collectors.joining("\n"));
                String reportName = declaration.getMediaCoverages().stream().map(DeclareMediaCoverage::getReportName).collect(Collectors.joining("\n"));
                String reportTime = declaration.getMediaCoverages().stream().map(DeclareMediaCoverage::getReportTime).collect(Collectors.joining("\n"));
                exportModel.setMediaName(mediaName);
                exportModel.setReportName(reportName);
                exportModel.setReportTime(reportTime);
            }

            exportList.add(exportModel);
        }
        return exportList;
    }

    /**
     * 项目排名列表
     * @param declarationZhejiang
     * @return
     */
    @ApiOperation("项目排名列表导出")
    @PostMapping("/ranking/list")
    public AjaxResult rankingList(@Validated @RequestBody DeclarationZhejiang declarationZhejiang) {
        List<DeclarationZhejiang> list = new ArrayList<>();
        if (declarationZhejiang.getId() != null){
            DeclarationZhejiang declaration = selectRankingOne(declarationZhejiang.getId());
            list = Arrays.asList(declaration);
        }else if (CollectionUtils.isNotEmpty(declarationZhejiang.getIdList())){
            for (Long id:declarationZhejiang.getIdList()){
                list.add(selectRankingOne(id));
            }
        }else {
            Integer pageNum = declarationZhejiang.getPageNum() != null ? declarationZhejiang.getPageNum() : 1;
            Integer pageSize = declarationZhejiang.getPageSize() != null ? declarationZhejiang.getPageSize() : 20000;
            String orderBy = "dr.score desc";
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
                PageHelper.startPage(pageNum, pageSize, orderBy);
            }

            if (declarationZhejiang.getAuditStatus() == null || declarationZhejiang.getAuditStatus() < 23) {
                declarationZhejiang.setAuditStatus(24);
            }
            declarationZhejiang.setDistributionStatus(1);
            list = declarationZhejiangService.getRankingDecorationList(declarationZhejiang);
        }
        ExcelUtil<DeclarationZhejiangRankingExport> util = new ExcelUtil<DeclarationZhejiangRankingExport>(DeclarationZhejiangRankingExport.class);
        List<DeclarationZhejiangRankingExport> exportList = new ArrayList<>();
        for (DeclarationZhejiang declaration:list){
            DeclarationZhejiangRankingExport exportModel = new DeclarationZhejiangRankingExport();
            BeanUtils.copyProperties(declaration,exportModel);
            if (CollectionUtils.isNotEmpty(declaration.getDeclareJudges())){
                if (declaration.getDeclareJudges().size() > 0){
                    exportModel.setExpert1(declaration.getDeclareJudges().get(0).getScore().doubleValue()/100);
                    exportModel.setRemark1(declaration.getDeclareJudges().get(0).getRemark());
                }
                if (declaration.getDeclareJudges().size() > 1){
                    exportModel.setExpert2(declaration.getDeclareJudges().get(1).getScore().doubleValue()/100);
                    exportModel.setRemark2(declaration.getDeclareJudges().get(1).getRemark());
                }
                if (declaration.getDeclareJudges().size() > 2){
                    exportModel.setExpert3(declaration.getDeclareJudges().get(2).getScore().doubleValue()/100);
                    exportModel.setRemark3(declaration.getDeclareJudges().get(2).getRemark());
                }
            }
            exportList.add(exportModel);
        }
        return util.exportExcel(exportList, "项目排名列表");
    }

//    public static void main(String[] args) {
//        Integer s1 = 1233;
//        System.out.println(s1.doubleValue()/100);
//    }

}
